from calc_manager.base.plugins import PluginObject
from minio import Minio
import os
from datetime import datetime
import io


class StoragePlugin(PluginObject):
    def __init__(self):
        self.save_prefix = "dc_storage_plugin"
        self.bucket = os.environ.get("OSS_BUCKET", "sh-dc")
        if os.environ.get("OSS_TYPE", "minio") == 'minio':
            self.client = Minio(
                endpoint=os.environ.get("OSS_ENDPOINT", "sp9.xuelangyun.com:30028"),
                access_key=os.environ.get("OSS_ACCESS_KEY", "Minio@edge"),
                secret_key=os.environ.get("OSS_SECRET_KEY", "Minio@edge"),
                secure=False
            )
        print("storage plugin init...")

    def save_file(self, file_path):
        object_name = f'{self.save_prefix}/{datetime.now().strftime("%Y%m%d")}/{os.path.basename(file_path)}'
        self.client.fput_object(self.bucket, object_name, file_path)
        return object_name

    def get_file(self, object_name, file_path):
        self.client.fget_object(self.bucket, object_name, file_path)

    def save(self, data: str):
        object_name = f'{self.save_prefix}/{datetime.now().strftime("%Y%m%d")}/{datetime.now().strftime("%H%M%S")}/data'
        data_stream = io.BytesIO(data.encode('utf-8'))
        self.client.put_object(self.bucket, object_name, data_stream, length=len(data), content_type="text/plain")
        return object_name

    def get(self, object_name) -> str:
        try:
            response = self.client.get_object(self.bucket, object_name)
            data = response.read().decode('utf-8')
            return data
        finally:
            response.close()
            response.release_conn()
